<template>
<div>
<!-- 个人中心负责人赵梦瑶 -->

<el-row class="bbbe" :gutter="20">
  <el-col :span="8"> <el-input clearable @input="search" @clear="search" placeholder="请输入内容" v-model="keys.query" class="input-with-select">
    
    <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
  </el-input></el-col>
  <el-col :span="4">  <el-button type="primary" @click="add">添加用户</el-button></el-col>

</el-row>
<el-table  :data="tableUser" >
  <el-table-column   type="index" label="#"></el-table-column>
  <el-table-column label="用户名"  prop="username"></el-table-column>
  <el-table-column label="邮箱" prop="email"></el-table-column>
  <el-table-column label="电话" prop="mobile"></el-table-column>
  <el-table-column label="角色" prop="role_name"></el-table-column>
  <el-table-column label="状态" prop="mg_satus">
      <template slot-scope="scope">
     <el-switch
  v-model="scope.row.mg_state"
   @change="changeUserStatus(scope.row)"
  active-color="#13ce66"
  inactive-color="#ff4949">
</el-switch>
        
         
       
      </template>
  </el-table-column>
  <el-table-column label="操作" width="150px">
      <template slot-scope="scope">
        <!-- 更新 -->
        <el-button
          size="mini"
          @click="handleEdit(scope.$index, scope.row)"
          type="primary" icon="el-icon-edit" circle>
          </el-button>
        <!-- 删除 -->
        <el-button
          size="mini"
          
           type="danger" icon="el-icon-delete" circle
          @click="handleDelete(scope.$index, scope.row)">
          </el-button>
        <!-- 权限 -->
          <el-button
          size="mini"
          @click="sove(scope.$index, scope.row)"
          type="warning" icon="el-icon-star-off" circle>
        </el-button>
      </template>
    </el-table-column>
</el-table>
 <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="keys.pagenum"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="keys.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
<!-- 弹出层 -->
<el-dialog
  :title="flag"
  :visible.sync="dialogVisible"
  width="30%"
  >
  <el-form ref="addForms" :model="addForm" 
  :rules="rules"
   label-width="80px">
    <el-form-item label="用户名" prop="username" >
       <el-input v-model="addForm.username" :disabled="flag1"
     placeholder="请输入用户名"
    prefix-icon="el-icon-user"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password" v-show="!flag1">
       <el-input
       v-model="addForm.password"
     placeholder="请输入密码"
    prefix-icon="el-icon-user"></el-input>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
       <el-input
       v-model="addForm.email"
     placeholder="请输入邮箱"
    prefix-icon="el-icon-user"></el-input>
    </el-form-item>
    <el-form-item label="电话" prop="mobile">
       <el-input
       v-model="addForm.mobile"
     placeholder="请输入内容"
    prefix-icon="el-icon-user"></el-input>
    </el-form-item>
    
   
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="useradd">确 定</el-button>
  </span>
</el-dialog>

<!-- 弹出层 -->
<!-- 弹出层 -->
<el-dialog
  title="分配角色"
  :visible.sync="dialogVisibles"
  width="30%"
  >
  <el-form :model="gosForm" 
 label-width="100px">
    <el-form-item label="当前的用户:" prop="username" >
        <span>{{gosForm.username}}</span> 
    
    </el-form-item>
    <el-form-item label="当前的角色:" prop="role_name" >
       <span>{{gosForm.role_name}}</span> 
    </el-form-item>
    
  </el-form>
  <div class="bs">
  <span class="bs1">分配新角色：</span>
     <el-select v-model="roleval" placeholder="请选择">
    <el-option
      v-for="item in roles"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>
  </div>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisibles = false">取 消</el-button>
    <el-button type="primary" @click="roleupdate">确 定</el-button>
  </span>
</el-dialog>

<!-- 弹出层 -->
</div>
</template>

<script>

import {userApi,adduserApi,addstatus,addupdate,userrole,adddelete,roles} from '@/http/api'
export default {
  name: '',  // 
 
  components: {},//引入子  
  data () {//数据
  //验证邮箱的函数
    const checkEmail = (rule, value, callback) => {
      //邮箱正则表达式
      const emailReg =
        /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/

      if (!emailReg.test(value)) {
        return callback(
          new Error('您输入的邮箱格式不合法，格式应该为：xxxxx@xxxx.com')
        )
      }

      callback()
    }

    //验证手机号函数
    const checkMobile = (rule, value, callback) => {
      //验证手机号的正则  \d 0-9
      const mobileReg = /^1[356789]\d{9}$/
      if (!mobileReg.test(value)) {
        return callback(new Error('您输入的手机号格式有误，请检查！'))
      }

      callback()
    }
    return {
        dialogVisible: false,//弹出框状态
        dialogVisibles: false,//弹出框状态
        flag:'添加用户',//弹出框判断状态
        flag1:false,
        total:12,
        roles:[],
        roleval:'',
         gosForm:{},
        id:-1,
        addForm:{
          username:'',
          password:'',
          email:'',
          mobile:'',
          

        },
        rules:{
           username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          {
            min: 3,
            max: 20,
            message: '用户名长度需要在3~20位之间',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          {
            min: 3,
            max: 20,
            message: '密码长度需要在3~20位之间',
            trigger: 'blur'
          }
        ],
        //邮箱
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        //电话
        mobile: [
          { required: true, message: '电话不能为空', trigger: 'blur' },
          { validator: checkMobile }
        ]
        },
        
        
      keys:{
        query:'',
        pagenum:1,
        pagesize:5,
      },
      //全部信息
      tableUser:[]
    }
  },
  created () {
    this.gets()
   },//todo钩子函数 实例创建之前 
  mounted () { },//真实dom挂载之后，运行，这时可以访问dom元素
  methods: {
    //权限赋值
    async sove(i,item){
      this.gosForm={...item}
      this.dialogVisibles=true
    const res=await roles()
    this.roles=res
    // console.log(res);
   

    },
    async roleupdate(){
       console.log('val:',this.roleval);
    const res=  await userrole(this.gosForm.id,{rid:this.roleval})
    console.log(res);
    this.gets()
    this.dialogVisibles=false
    }
    ,
    //状态更新
    async changeUserStatus(row){
     const res= await addstatus(row.id,row.mg_state) 
      this.gets()
    },

    // 数据条数
    handleSizeChange(w){
  
      this.keys.pagesize=w
      this.gets()
    },
    //页数回调
    handleCurrentChange(w){
  
      this.keys.pagenum=w
      this.gets()
    }
    ,
    add(){
      this.dialogVisible=true;
      this.flag='添加用户'
      this.flag1=false
      this.addForm={
        username:'',
          password:'',
          email:'',
          mobile:'',
      }
    },//添加按钮
    useradd(){
      
       this.$refs.addForms.validate(async (valid) => {
        //如果不合法，保留在当前对话框
        if (!valid) return false
        if(this.flag=="添加用户"){
           const res = await adduserApi(this.addForm)
        console.log('添加的结果：', res)
        }else{

          const res= await addupdate(this.id,{mobile:this.addForm.mobile,email:this.addForm.email})
          console.log('添加的结果：', res)
        }

        //合法，则调用添加用户接口，将数据保存到后台数据库
       

        //隐藏对话框
        this.dialogVisible = false

        //更新用户列表
        this.gets()

      })
    },
    // 获取页面信息
    search: _.debounce(function(){
      this.gets()
    },2000),
    async gets(){
     const res= await userApi(this.keys)
     console.log('res',res);
      this.tableUser=res.users
      this.total=res.total
    },
    handleEdit(id,item){
      console.log(id,item);
        this.dialogVisible = true 
        this.flag="编辑用户"
        this.flag1=true
        this.addForm={...item,password:'123456'}
        this.id=item.id
          

    },
  handleDelete(id,item){
    this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then( async () => {
          const res= await adddelete(item.id)
  this.gets()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
  }
  },//!事件函数
  computed:{} , //计算属性
  watch:{ //监听属性
   a: {
deep: true,
immediate: true,
handler(newval){},
}
}
}
</script>
<style scoped lang='scss'>
// 个人中心负责人赵梦瑶

.bs{
display: flex;
justify-content: flex-start;
.bs1{
  display: inline-block;
  width: 120px;
}
}

.bbbe{
  margin-bottom: 10px;
}
</style>
